// import { TButton, TDialog, TPopupProxy, TTable } from 't';
import TButton from 't/basic/button';
import TDialog from 't/basic/dialog';
import TPopupProxy from 't/basic/popup-proxy';
import TTable from 't/basic/table';
import { computed, defineComponent, onMounted, ref, toRefs, watch } from 'vue';
import HistoryComponent from './HistoryComponent';
import PreviewResult from './PreviewResult';
import SearchResult from './SearchResult';
import SingleRow from './SingleRow';
import TMenu from '@teld/q-components/Menu'
import { useQuasar } from '@teld/q-components';
export default defineComponent({
  name: 'SelectHelperSmallSizeRender',
  components: {
    TPopupProxy,
    TTable,
    HistoryComponent,
    SingleRow,
    TButton,
    TDialog,
    PreviewResult,
    SearchResult,
  },
  props: {
    simple: {
      type: Boolean,
      default: true,
    },
     width: {
      type: [String, Number],
      default:'1'
    },
    multiple: Boolean,
    height: String,
    position: String,
    historyEnable: Boolean,
    value: {
      type: [Array, String],
    },
    checkList: {
      type: [Array, String, Object],
    },
    columns: {
      type: Array,
    },
    valueField: String,
    labelField: String,
    helperCode: String,
    placeholder: String,
    searchEnable: Boolean,
    searchPosition: String,
    subsidiary: String,
    countPerPage: String,
    pagination: Boolean,
    iconEnable: Boolean,
    iconDataSource: String,
    iconFiled: String,
    maxCheckedLength:[String,Number],
    showChecked:Boolean,
    filter:String,
    isCloseIng:Boolean
  },
  emits: ['update:checkList','update:isCloseIng'],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const $q = useQuasar();
    const {
      simple,
      width,
      multiple,
      height,
      position,
      historyEnable,
      value,
      checkList,
      columns,
      valueField,
      labelField,
      helperCode,
      placeholder,
      searchEnable,
      searchPosition,
      subsidiary,
      countPerPage,
      pagination,
      iconEnable,
      iconDataSource,
      iconFiled,
      maxCheckedLength,
      showChecked,
      filter,
      isCloseIng
    } = toRefs(props);

    const refTPopupProxy = ref(null);
    const selection = ref([]);

    const show = () => {
      refTPopupProxy.value&&refTPopupProxy.value.show();
    };
    const close = () => {

      emit('update:isCloseIng', true);
      refTPopupProxy.value&&refTPopupProxy.value.hide();
      setTimeout(() => {
        emit('update:isCloseIng', false);
      }, 1000);
    };
    // const filter = ref('');
    const getDateByFilter=()=>{
      if (rows.value && rows.value == 1) {
        selectList.value=rows.value
        emit('update:checkList', selectList.value);
        close();
      }

    }
    expose({
      show,
      close,
      getDateByFilter
    });
    onMounted(() => {});

    function onClickHandler(params) {}
    //简单模式
    const columnsByComputed = computed(() => {
      return columns.value && columns.value.length > 0
        ? columns.value
            .map(item => {
              if (item.isShow && item.dataField == labelField.value) {
                return {
                  name: item.dataField,
                  required: true,
                  label: item.caption,
                  align: item.textAlign ? item.textAlign : 'left',
                  field: item.dataField,
                  width: item.width ? item.width : '',
                  // sortable: true,
                  // sort: (a, b) => parseInt(a, 10) - parseInt(b, 10),
                };
              }
            })
            .filter(item => item)
        : [
            {
              name: labelField.value,
              required: true,
              label: labelField.value,
              align: 'left',
              field: labelField.value,
              width: '',
              // sortable: true,
              // sort: (a, b) => parseInt(a, 10) - parseInt(b, 10),
            },
          ];
    });
    const computedHeight = computed(() => {
      // let _height = height.value ? height.value : '80vh'
      // if (_height.indexOf('%') > -1) {
      //   _height = _height.replace('%', 'vh')
      // }
      return '288px' ;

    })
    const generateSimple = () => {
      return (
        <single-row
          width={'100vw'}
          multiple={multiple.value}
          simple={simple.value}
          onUpdateSelectList={e => {
            selectList.value = e;
          }}
          checkList={selectList.value}
          placeholder={placeholder.value}
          columns={columnsByComputed.value}
          labelField={labelField.value}
          valueField={valueField.value}
          filter={filter.value}
          subsidiary={subsidiary.value}
          ref={refComponent}
          countPerPage={countPerPage.value}
          pagination={pagination.value}
          iconEnable={iconEnable.value}
          iconDataSource={iconDataSource.value}
          targetSelection={selection.value}
          targetSelectList={selectList.value}
          height={computedHeight.value}

        />
      );
    };
    //已选择数据集合
    const selectList = ref([]);
    // watch(
    //   () => value.value,
    //   () => {
    //     //计算当前数据，实现数据回显
    //     selectList.value = value.value;
    //   },
    // );
    watch(
      () => selectList.value,
      () => {

        if (multiple.value) {
          selection.value = selectList.value.map(
            item => item[valueField.value],
          );
          emit('update:checkList', JSON.parse(JSON.stringify(selectList.value)));
           return
        }
        emit('update:checkList', JSON.parse(JSON.stringify(selectList.value)));
        close();
        // emit('update:value', selectList.value);
      },
      {
        deep: true,
        // immediate: true,
      },
    );
    const selectList_proxy = ref([]);
    watch(
      () => checkList.value,
      () => {
        if (JSON.stringify(selectList.value)==JSON.stringify(checkList.value)) return
        //计算当前数据，实现数据回显
        if (!simple.value) {
          selectList_proxy.value = checkList.value
          selectList.value = JSON.parse(JSON.stringify(selectList_proxy.value))
        } else {
          selectList.value = JSON.parse(JSON.stringify(checkList.value))
        }

      },
      {
        deep: true,
        immediate: true,
      }
    );
    //定义点击事件
    const trTargetClick = target => {
      if (selectList.value.some(item => item.name == target.name)) {
        selectList.value = selectList.value.filter(
          item => item.name != target.name,
        );
      } else {
        if (!multiple.value) {
          selectList.value = [];
        }
        selectList.value.push(target);
      }
    };
    const checkAll = computed(() => {
      if (rows.every(item => selection.value.some(sel => item.name == sel))) {
        return ['ischecked'];
      } else if (
        !rows.some(item => selection.value.some(sel => item.name == sel))
      ) {
        return [];
      }
      return null;
    });
    if (multiple.value) {
      watch(
        () => selectList.value,
        () => {
          console.log(selectList.value);
          selection.value = selectList.value.map(item => item[valueField.value]);
        },
        {
          deep: true,
        },
      );
    }

    //生成内容区域
    const generateContent = () => {
      if (isShow.value) {
        return generateSimple();
      } else {
        return <div style={`height:${computedHeight.value};flex:1 1 auto`}>
          <t-inner-loading
            showing={true}
            label={$q.lang.mixedView.chartLoading}
            label-class='text-teal'
            label-style='font-size: 1.1em'
          />
        </div>
      }
    };
    const refPreview = ref();
    const refSearch = ref();
    const isShow = ref(false);
    return () => {
      return (
        <t-menu
          ref={refTPopupProxy}
          class='select_helper_popup select_helper_popup_menu select_helper_popup_m'

          style="left:0;right:0;100vw"
          onBeforeShow={() => {

            isShow.value=true

          }}
          onBeforeHide={() => {
            close()
            isShow.value=false
          }}
        >
            <div>
              {generateContent()}
            </div>

        </t-menu>
      );
    };
  },
});
